package linkedlist.leetcode_148_medium;

public class MergeSort {
    public ListNode sortList(ListNode head) {
        //递归出口，当下一个节点为 null时，说明没有下一个节点，返回当前节点
        if(head == null || head.next == null){
            return head;
        }
        ListNode fast = head;
        ListNode slow = head;
        //快慢指针找中点
        while(fast.next != null && fast.next.next != null){
            fast = fast.next.next;
            slow = slow.next;
        }
        //找到链表的中间，一分为二，递归分割整个链表。
        ListNode temp = slow.next;
        slow.next = null;
        ListNode left = sortList(head);
        ListNode right = sortList(temp);

        return mergeTwoList(left,right);
    }
    public ListNode mergeTwoList(ListNode l1, ListNode l2){
        if(l1 == null || l2 == null){
            return l1 != null ? l1 : l2;
        }
        if(l1.val < l2.val){
            l1.next = mergeTwoList(l1.next,l2);
            return l1;
        }else{
            l2.next = mergeTwoList(l1,l2.next);
            return l2;
        }
    }
}
